<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    // 输入：l1 = [2,4,3],     342 + 465 = 807
    //      l2 = [5,6,4]
    // 输出：    [7,0,1,1]
    // 这里的每一个数字 都是一个对象  val是他自己 next是下一个值
    function ListNode(val, next) {
      this.val = val === undefined ? 0 : val;
      this.next = next === undefined ? null : next;
    }

    let b = new ListNode(3, null);
    let a = new ListNode(4, b);
    let l1 = new ListNode(2, a);
    let d = new ListNode(4, null);
    let c = new ListNode(6, d);
    let l2 = new ListNode(5, c);

    console.log(Solution(l1, l2), "结果");
    function Solution(l1, l2) {
      let count = null; //当前的对象
      let head = null; //第一个对象
      let addOne = 0; // 进位数
      while (l1 != null || l2 != null) {
        let sum = (l1?.val ?? 0) + (l2?.val ?? 0) + addOne;
        if (!head) {
          head = count = new ListNode(sum % 10);
        } else {
          count = count.next = new ListNode(sum % 10);
        }
        addOne = Math.floor(sum / 10);
        if (l1) {
          l1 = l1.next;
        }
        if (l2) {
          l2 = l2.next;
        }
      }
      if (addOne == 1) {
        count.next = new ListNode(1);
      }
      return head;
    }
  </script>
</html>
